<!--
 * @Descripttion: 
 * @version: 
 * @Author: weni09
 * @Date: 2021-05-27 11:30:51
 * @LastEditors: weni09
 * @LastEditTime: 2021-06-17 11:19:50
 * @FilePath: \icoder-frontend\blog\src\views\ArticleEdit.vue
-->
<template>
  <div class="art-editor">
    <el-form :model="articleForm" 
    status-icon 
    label-position="left"
     ref="articleForm"
     label-width="6rem" 
     :modal-append-to-body="true"
     :rules="rules"
     class="articleForm"
     >
     <div class="row-1 d-flex">
    <el-form-item label-width="0" prop="title" class="form-title" style="width:80%">
      <el-input class="el-input-title" v-model="articleForm.title" autocomplete="off" placeholder="请输入标题"></el-input>
    </el-form-item>
    <el-form-item class="article-submit-prop btn" label-width="0" style="width:10%">
 		  <el-button class="submit-btn" 
       type="danger"
       size="medium"
       :disabled="disabled"
       :loading="loading"
       @click="submitArticleForm('articleForm')" 
    >{{submitBtnText}}</el-button>
 		</el-form-item>
     </div>
    <el-form-item label-width="0px" prop="summary" class="form-summary">
      <el-input class="el-input-summary"
      type="textarea"
      :rows="3" 
      v-model="articleForm.summary"
      autocomplete="off"
      placeholder="请输入摘要,限制200字符以内"></el-input>
    </el-form-item>
    <div class="art-other">
     <el-form-item 
     label="是否公开:" 
     prop="is_public" 
     class="art-other-right"
     >
      <el-tooltip :content="articleForm.is_public==true ? '公开':'不公开'" placement="top">
       <el-switch class="pub-switch"
        v-model="articleForm.is_public"
        :active-value="true"
        :inactive-value="false"
        active-color="#13ce66"
        inactive-color="#ff4949">
        </el-switch>
    </el-tooltip>
    </el-form-item>

     <el-form-item 
     label="是否置顶:" 
     prop="is_top" 
     class="art-other-right"
     >
      <el-tooltip :content="articleForm.is_top ? '置顶':'不置顶'" placement="top">
       <el-switch class="pub-switch"
        v-model="articleForm.is_top"
        :active-value="true"
        :inactive-value="false"
        active-color="#13ce66"
        inactive-color="#ff4949">
        </el-switch>
    </el-tooltip>
    </el-form-item>
    <el-form-item label="分类:" label-width="4rem" prop="category_id" class="art-other-right"> 
      <el-select v-model="articleForm.category_id" placeholder="选择分类" clearable filterable>
    <el-option
      v-for="item in categorys"
      :key="item.id"
      :label="item.name"
      :value="item.id">
    </el-option>
     </el-select>
    </el-form-item>
    <el-form-item label="标签:" label-width="3rem" prop="selectedTags" class="art-tag">
    <el-select
    v-model="articleForm.selectedTags"
    multiple
    filterable
    allow-create
    default-first-option
    :placeholder="tagPlaceholder"
    class="select-tag">
    <el-option
      v-for="item in tags"
      :key="item.id"
      :label="item.name"
      :value="item.id">
    </el-option>
  </el-select>
    </el-form-item>
    </div>
  <div class="art-other banner">
  <el-form-item label="Banner图片:" prop="img_link" class="form-img-link">
      <el-input class="el-input-img-link" v-model="articleForm.img_link" autocomplete="off" placeholder="Banner图片链接，可上传，非必需"></el-input>
  </el-form-item>
      <div class="upload-btn" style="margin-left:1rem">
      <el-upload
      class="upload-demo art-other"
      :action="imgUploadUrl"
      name="image"
      :headers="{Authorization:'Bearer ' + $store.getters.auth.token}"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :before-remove="beforeRemove"
      :limit="1"
      :on-exceed="handleExceed"
      accept="image/jpeg,image/gif,image/png">
      <el-button size="medium" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip" style="margin-left:0.5rem">只能上传jpg/png文件，且不超过1MB</div>
      </el-upload>
      </div>
  </div>
      <el-form-item label-width="0px" prop="body_md">
        <mavonEditor ref="md"  class="md" minHeight="600px"></mavonEditor>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import mavonEditor from 'components/MavonEditor';
import {fetchTags,fetchCategories,addArticle,deleteFile} from 'api';
import {removeBlank} from '@/utils';
export default {
  data(){
     var checkIsNull = (rule,value,callback)=>{
       var value = removeBlank(value)
      //  console.log(value)
       if (!value){
          return callback(new Error('内容不能为空'));
       }
       else{
         callback();
       }
     };
    return{
      articleForm:{
          title:"",
          summary:"",
          is_public:false,
          is_top:false,
          category_id:"",
          selectedTags:[],
          body_md:"",
          body:"",
          author_id:"",
          img_link:"",
      },
      rules:{
        title:[{required: true,validator:checkIsNull,trigger: 'blur'}],
        summary:[{required: true,validator:checkIsNull,trigger: 'blur'}],
        is_public:[{required: true,}],
        category_id:[{required: true,validator:checkIsNull,trigger: 'blur'}],
        body_md:[{required: true,message: '内容不能为空'}], 
      },
      categorys:[],
      tags:[],
      imgUploadUrl: process.env.NODE_ENV === 'production' ? process.env.VUE_APP_API : process.env.VUE_APP_API_DEV + "/file/upload",
      submitBtnType : "danger",
      submitBtnText: "发布文章",
      disabled: false,
      loading: false,
      tagPlaceholder:"选择文章标签,可搜索,可直接输入添加",
      
      }
  },

  components: {
    mavonEditor
  },

  methods:{
    queryTags(){
       fetchTags().then(res => {
          this.tags = res.data || []
				}).catch(err => {
                console.log(err)
        })
    },
    queryCategorys(){
       fetchCategories().then(res => {
          this.categorys = res.data || []
				}).catch(err => {
             console.log(err)
        })
    },
    queryArticle(){
      // console.log(this.$route.params)
      let artDetail = this.$store.getters.artDetail
      if(this.$route.params.id && artDetail){
        let fileds = ['title','summary','is_public','is_top','category_id','body_md','body','author_id','img_link']
        for (let key in artDetail){
            if (fileds.indexOf(key) != -1){
              this.articleForm[key] = artDetail[key]
            } 
        }
        this.articleForm['art_id'] = this.$route.params.id
        this.$refs.md.content = artDetail.body_md
        this.$refs.md.html = artDetail.body
        for (let i in artDetail.tags){
          this.articleForm.selectedTags[i] = artDetail.tags[i].tags__id
        }
        // console.log(this.articleForm.selectedTags.length)
        if (this.articleForm.selectedTags.length!=0){
          this.tagPlaceholder = ""
        }
        // console.log(this.articleForm )
      }
    },
    //初始化数据
   initData(){
    this.queryCategorys();
    this.queryTags();
    this.queryArticle();
   },
  submitting(){
   this.submitBtnText="发布中...";
   this.disabled = true;
   this.loading = true;
  },
  initSubmitBtn(){
    this.submitBtnText="发布文章";
    this.disabled = false;
    this.loading = false;
  },
  myNotify(type,text){
        this.$notify({
        position: 'top-left',//左上方显示
        type:type,
        duration:2000, //显示3秒自动消失
        showClose:false, //不显示关闭按钮
        message:text, //显示的消息
        offset:100, //到顶部的偏移量
      })
  },
  //重置表单
  resetForm(formName) {
    this.$refs[formName].resetFields();
    this.$refs.md.content="";
    this.$refs.md.html="";
  },
  //提交新增文章
  submitArticleForm(formName){
    this.$refs[formName].model.body_md = this.$refs.md.content
    this.$refs[formName].model.body = this.$refs.md.html
    
    this.$refs[formName].validate((valid)=>{
    if(valid){
    this.submitting()
    // console.log(this.$refs.md)
    // console.log("articleForm: " + JSON.stringify(this.$refs[formName].model))
    for (let i in this.articleForm.selectedTags){
      for (let j in this.tags){
          if (removeBlank(this.articleForm.selectedTags[i]).toLowerCase() == removeBlank(this.tags[j].name).toLowerCase()){
            this.articleForm.selectedTags[i] = this.tags[j].id
          }
      }
    };
    this.articleForm.selectedTags = Array.from(new Set(this.articleForm.selectedTags))
    this.$refs[formName].model.author_id = this.$store.getters.auth.user_id
    
    addArticle(this.$refs[formName].model).then(res=>{
      this.myNotify('success',`发布文章${this.articleForm.title}成功`);
      this.initSubmitBtn();
      this.resetForm(formName);
      // console.log("response articleId: "+res.data.id)
      if (res.data.id){
      this.$router.push("/artDetail/"+res.data.id)
      }
    }).catch(err=>{
      this.myNotify('error',`发布文章${this.articleForm.title}失败`);
      this.initSubmitBtn();
      console.log("addArticle: " + err)
    })
    }
    else{
      return false
    }
    });
  },
  handleSuccess(res, file) {
    if (res.data && res.data.url){
        // this.filelist = [{name:res.data.alt,url:res.data.url}]
        this.articleForm.img_link = res.data.url
        // console.log(this.articleForm.img_link)
    }
  },
  handleRemove(file) {
    let params={
      path:this.articleForm.img_link
    }
    // console.log(file)
    deleteFile(params).then(res=>{
    this.articleForm.img_link = "";
    // console.log("deleteFile：",res)
    }).catch(err=>{
    // this.$message.error("删除失败");
    this.$notify({
        position: 'top-left',//左上方显示
        type:"error",
        duration:3000, //显示3秒自动消失
        showClose:false, //不显示关闭按钮
        message:`删除${file.name}失败`, //显示的消息
        offset:100, //到顶部的偏移量
      })
    console.log("deleteFile：",err)
    })
    // console.log(file, fileList);
  },

  handleExceed(files, fileList) {
        this.$message.warning("当前限制选择 1 个文件");
  },
  beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
  }

},

updated(){
  // this.queryArticle();
},
  mounted(){
    this.initData();
  }
}
</script>

<style lang="scss" scoped>
.art-editor{
  padding: 0 10px;
}
// .form-title :first-child {
//     display: flex;
// }

.submit-btn{
  margin: 0 2rem;
}
.art-other{
  display: flex;
}
.art-other-right{
  margin-right: 30px;
}
.art-tag{
  width: 50%;
}
.select-tag{
  width: 100%;
}
.form-img-link{
  width:30%;
}

</style>